package com.leap.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leap.entity.Media;
import com.leap.entity.dto.ArticleUploadDTO;
import com.leap.entity.dto.MediaUploadDTO;
import com.leap.mapper.ArticleMapper;
import com.leap.mapper.MediaMapper;
import com.leap.service.MediaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MediaServiceImpl extends ServiceImpl<MediaMapper, Media> implements MediaService {

    @Autowired
    private MediaMapper mediaMapper;

    @Autowired
    private ArticleMapper articleMapper;

    @Override
    public List<Media> getMediasByArticleId(Long id) {
        List<Media> mediaList = mediaMapper.selectByArticleId(id);
        return mediaList;
    }

    @Override
    public Media getCoverById(Long articleId) {
        Long coverId = mediaMapper.getCoverById(articleId);
        Media media = mediaMapper.selectById(coverId);
        return media;
    }

    @Override
    public void saveMedia(ArticleUploadDTO articleDTO, Long articleId) {
        int order = 1;
        List<MediaUploadDTO> mediaList = articleDTO.getMediaUrl();
        if (mediaList.size() == 0) {
            return;
        }
        for (MediaUploadDTO mediaUploadDTO : mediaList) {
            Media media = Media.builder()
                    .mediaType(mediaUploadDTO.getMediaType())
                    .duration(mediaUploadDTO.getDuration())
                    .mediaUrl(mediaUploadDTO.getFileUrl()==null?null:mediaUploadDTO.getFileUrl())
                    .build();
            mediaMapper.insert(media);
            Long mediaId = media.getId();
            if (order == 1){
                articleMapper.insertArticleMediaDTO(articleId,mediaId,order,1);
            }else{
                articleMapper.insertArticleMediaDTO(articleId,mediaId,order,0);
            }
            order++;
        }
    }

    @Override
    public boolean deleteMedia(Long articleId) {
        List<Media> mediaList = this.getMediasByArticleId(articleId);
        if (mediaList.size() == 0) {
            return false;
        }
        for (Media media : mediaList) {
            mediaMapper.deleteByUrl(media.getMediaUrl());
        }

        int delete = mediaMapper.deleteByArticleId(articleId);
        System.out.println(delete);
        return true;
    }
}
